package com.ChainBizPro.system.service.impl;

import com.ChainBizPro.system.common.ErrorCode;
import com.ChainBizPro.system.exception.BusinessException;
import com.ChainBizPro.system.mapper.PurchaseOrdersMapper;
import com.ChainBizPro.system.model.domain.*;
import com.ChainBizPro.system.model.dto.Order.OrdersQueryRequest;
import com.ChainBizPro.system.model.dto.Order.PurchaseOrdersAddRequest;
import com.ChainBizPro.system.model.dto.Order.OrderPaymentQueryRequest;
import com.ChainBizPro.system.model.enums.PaymentStatusEnum;
import com.ChainBizPro.system.model.vo.PurchaseOrderVO;
import com.ChainBizPro.system.model.vo.PurchaseOrdersVO;
import com.ChainBizPro.system.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author liusijia
 * @description 针对表【purchase_orders(采购订单)】的数据库操作Service实现
 * @createDate 2024-11-16 16:34:17
 */
@Service
public class PurchaseOrdersServiceImpl extends ServiceImpl<PurchaseOrdersMapper, PurchaseOrders>
        implements PurchaseOrdersService {

    @Resource
    @Lazy
    private PurchaseOrdersService purchaseOrdersService;

    @Resource
    private UserService userService;

    @Resource
    private SuppliersService suppliersService;

    @Resource
    private StockService stockService;

    @Resource
    private StockTransactionsService stockTransactionsService;

    @Resource
    private PurchaseOrdersMapper purchaseOrdersMapper;

    @Override
    public Page<PurchaseOrders> getQueryWrapper(Page<PurchaseOrders> page, OrdersQueryRequest orderIdQueryRequest,
            long userId) {
        if (orderIdQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        QueryWrapper<PurchaseOrders> queryWrapper = new QueryWrapper<>();

        addLikeCondition(queryWrapper, "supplierName", orderIdQueryRequest.getSupplierName());
        addLikeCondition(queryWrapper, "productName", orderIdQueryRequest.getProductName());

        if (orderIdQueryRequest.getQuantity() != null) {
            queryWrapper.like("quantity", orderIdQueryRequest.getQuantity());
        }
        if (orderIdQueryRequest.getUnitPrice() != null) {
            queryWrapper.like("unitPrice", orderIdQueryRequest.getUnitPrice());
        }
        if (orderIdQueryRequest.getStatus() != null) {
            queryWrapper.like("status", orderIdQueryRequest.getStatus());
        }
        queryWrapper.eq("userId", userId);
        // 过滤 userId 为当前登录用户的 ID
        queryWrapper.orderByDesc("orderId");

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public PurchaseOrdersVO getPurchaseOrdersVO(PurchaseOrders purchaseOrders) {
        if (purchaseOrders == null) {
            return null;
        }
        PurchaseOrdersVO purchaseOrdersVO = new PurchaseOrdersVO();
        BeanUtils.copyProperties(purchaseOrders, purchaseOrdersVO);
        return purchaseOrdersVO;
    }

    @Override
    public Page<PurchaseOrderVO> getQueryWrapperByAdmin(Page<PurchaseOrderVO> pageParam,
            OrdersQueryRequest ordersQueryRequest) {
        // 自定义分页查询
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdersMapper.getQueryWrapperByAdmin(pageParam,
                ordersQueryRequest);
        if (purchaseOrderVOS == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询失败");
        }
        for (PurchaseOrderVO vo : purchaseOrderVOS) {
            if ("pending".equals(vo.getStatus())) {
                vo.setStatus("进行中");
            }
            if ("completed".equals(vo.getStatus())) {
                vo.setStatus("已完成");
            }
            if ("cancelled".equals(vo.getStatus())) {
                vo.setStatus("已取消");
            }
        }
        // 设置分页结果
        pageParam.setRecords(purchaseOrderVOS);
        return pageParam;
    }

    @Override
    public boolean addPurchaseOrders(PurchaseOrdersAddRequest purchaseOrdersAddRequest, HttpServletRequest request) {
        try {
            // 获取当前用户
            User user = userService.getLoginUser(request);
            Suppliers supplier = new Suppliers();
            Stock stock = new Stock();
            PurchaseOrders purchaseOrder = new PurchaseOrders();
            purchaseOrder.setUserId(user.getId());

            QueryWrapper<Suppliers> querySupplier = new QueryWrapper<>();
            QueryWrapper<Stock> queryStock = new QueryWrapper<>();
            querySupplier.eq("supplierName", purchaseOrdersAddRequest.getSupplierName());
            queryStock.eq("productName", purchaseOrdersAddRequest.getProductName());
            supplier = suppliersService.getOne(querySupplier);
            stock = stockService.getOne(queryStock);

            if (supplier == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "供应商不存在");
            }
            if (stock == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "商品不存在");
            }

            // 检查请求参数的有效性
            if (purchaseOrdersAddRequest.getQuantity() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "数量必须为正数");
            }

            // 更新商品库存数量
            stock.setQuantity(stock.getQuantity() - purchaseOrdersAddRequest.getQuantity());
            stockService.updateById(stock);

            // 插入库存交易表
            StockTransactions stockTransactions = new StockTransactions();
            stockTransactions.setProductId(stock.getProductId());
            stockTransactions.setTransactionType("out"); // 出库
            stockTransactions.setQuantity(purchaseOrdersAddRequest.getQuantity());
            stockTransactionsService.save(stockTransactions);

            // 保存采购订单
            purchaseOrder.setSupplierId(supplier.getSupplierId());
            purchaseOrder.setUnitPrice(stock.getUnitPrice());
            BeanUtils.copyProperties(purchaseOrdersAddRequest, purchaseOrder);
            boolean result = purchaseOrdersService.save(purchaseOrder);

            return result;
        } catch (BusinessException e) {
            // 处理 BusinessException
            throw e;
        } catch (Exception e) {
            // 处理其他异常
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        }
    }

    @Override
    public Page<PurchaseOrderVO> getQueryWrapperByUser(Page<PurchaseOrderVO> pageParam,
            OrdersQueryRequest orderQueryRequest, Long userId) {
        // 自定义分页查询
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdersMapper.getQueryWrapperByUser(pageParam,
                orderQueryRequest, userId);
        if (purchaseOrderVOS == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询失败");
        }

        // 转换状态
        for (PurchaseOrderVO vo : purchaseOrderVOS) {
            // 转换订单状态
            if ("pending".equals(vo.getStatus())) {
                vo.setStatus("进行中");
            }
            if ("completed".equals(vo.getStatus())) {
                vo.setStatus("已完成");
            }
            if ("cancelled".equals(vo.getStatus())) {
                vo.setStatus("已取消");
            }

            // 转换支付状态
            String paymentStatus = (String) vo.getPaymentStatus();
            vo.setPaymentStatus(PaymentStatusEnum.getValueByCode(paymentStatus));
        }

        // 设置分页结果
        pageParam.setRecords(purchaseOrderVOS);
        return pageParam;
    }

    @Override
    public Page<PurchaseOrderVO> getOrdersByPaymentStatus(Page<PurchaseOrderVO> pageParam,
            String paymentStatus, OrderPaymentQueryRequest queryRequest, Long userId) {
        // 查询订单
        List<PurchaseOrderVO> orderVOS = purchaseOrdersMapper.getOrdersByPaymentStatus(
                pageParam, paymentStatus, queryRequest, userId);
        if (orderVOS == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询失败");
        }

        // 转换状态
        for (PurchaseOrderVO vo : orderVOS) {
            // 转换订单状态
            if ("pending".equals(vo.getStatus())) {
                vo.setStatus("进行中");
            }
            if ("completed".equals(vo.getStatus())) {
                vo.setStatus("已完成");
            }
            if ("cancelled".equals(vo.getStatus())) {
                vo.setStatus("已取消");
            }

            // 转换支付状态
            vo.setPaymentStatus(PaymentStatusEnum.getValueByCode((String) vo.getPaymentStatus()));
        }

        pageParam.setRecords(orderVOS);
        return pageParam;
    }

    private void addLikeCondition(QueryWrapper<PurchaseOrders> queryWrapper, String column, String value) {
        if (!StringUtils.isEmpty(value)) {
            queryWrapper.like(column, value);
        }

    }
}
